package org.example.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.embedded.EmbeddedChannel;
import org.example.utils.LogUtils;

public class InHandlerDemoTester {
    public static void main(String[] args) throws Exception{

        ChannelHandler ch = new ChannelInitializer<EmbeddedChannel>() {
            @Override
            protected void initChannel(EmbeddedChannel ch) throws Exception {
                ch.pipeline().addLast(new InHandler());
            }
        };
        // 会自动把channel加入到pipeline中
        EmbeddedChannel ech = new EmbeddedChannel(ch);

        ByteBuf buf = Unpooled.buffer();
        buf.writeInt(10);
        ech.writeInbound(buf);
        ech.flush();
        // 再次入站
        buf.writeInt(20);
        ech.writeInbound(buf);
        ech.flush();
    }

    static class InHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            LogUtils.info("读取数据");
            ByteBuf buf = (ByteBuf) msg;
            while (buf.isReadable()) {
                System.out.print(buf.readByte());
            }
            System.out.println();
            super.channelRead(ctx, msg);
        }

        @Override
        public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
            LogUtils.info("channel注册成功后注册");
            super.channelRegistered(ctx);
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            super.channelActive(ctx);
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            LogUtils.info("channel读取完毕回调");
            super.channelReadComplete(ctx);
        }
    }
}
